package com.sls.mall.coupon.service.impl;

import com.sls.mall.coupon.entity.SeckillSkuRelationEntity;
import com.sls.mall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sls.common.utils.PageUtils;
import com.sls.common.utils.Query;

import com.sls.mall.coupon.dao.SeckillSessionDao;
import com.sls.mall.coupon.entity.SeckillSessionEntity;
import com.sls.mall.coupon.service.SeckillSessionService;
import sun.util.resources.LocaleData;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Autowired
    SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLates3DaySession() {
        List<SeckillSessionEntity> sessionEntities = this.baseMapper.selectList(new QueryWrapper<SeckillSessionEntity>()
                .between("start_time", getStartTime(), getEndTime()));
        List<SeckillSessionEntity> collect = sessionEntities.stream().map(session -> {
            Long id = session.getId();
            List<SeckillSkuRelationEntity> skuRelationEntities = seckillSkuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", id));
            session.setRelationSkus(skuRelationEntities);
            return session;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 开始时间
     * @return
     */
    private String getStartTime(){
        LocalDate now = LocalDate.now();
        LocalTime min = LocalTime.MIN;
        LocalDateTime dateTime = LocalDateTime.of(now, min);
        String s = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        return s;
    }

    /**
     * 获取2天后的结束时间
     * @return
     */
    private String getEndTime(){
        LocalDate now = LocalDate.now();
        LocalDate date = now.plusDays(2);
        LocalTime min = LocalTime.MAX;
        LocalDateTime dateTime = LocalDateTime.of(date, min);
        String format = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        return format;
    }
}